package com.snap.awesomeserial.logger;

import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.LogStrategy;
import com.snap.awesomeserial.AppConfig;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Locale;

import static com.snap.awesomeserial.logger.Utils.checkNotNull;

public class ExpFormatStrategy implements FormatStrategy {

    private static final String NEW_LINE = System.getProperty("line.separator");

    private final SimpleDateFormat dateFormat;
    private final LogStrategy logStrategy;

    ExpFormatStrategy() {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

        String folder = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separatorChar + AppConfig.EXP_LOG_DIRECTORY;
        HandlerThread ht = new HandlerThread("AndroidFileLogger." + folder);
        ht.start();
        Handler handler = new ExpLogStrategy.WriteHandler(ht.getLooper(), folder);
        logStrategy = new ExpLogStrategy(handler);
    }

    @Override
    public void log(int priority, @Nullable String onceOnlyTag, @NonNull String message) {
        checkNotNull(message);

        StringBuilder builder = new StringBuilder();
        builder.append("[");
        builder.append(dateFormat.format(System.currentTimeMillis()));
        builder.append("] ");
        builder.append(message);

        // new line
        builder.append(NEW_LINE);

        logStrategy.log(priority, onceOnlyTag, builder.toString());
    }
}
